import re
import pandas as pd
from tkinter import filedialog
import tkinter as tk

def select_input_file_path():
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename(
        title="选择txt输入文件位置",
        defaultextension=".txt",
        filetypes=[("txt files", "*.txt"), ("All files", "*.*")],
    )
    return file_path

def select_output_file_path():
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.asksaveasfilename(
        title="选择excel文件保存位置",
        defaultextension=".xlsx",
        filetypes=[("xlsx files", "*.xlsx"), ("All files", "*.*")],
    )
    return file_path

# 定义关键字变量
KEYWORD = "542B"  # 可以在这里修改关键字

# 输入和输出文件位置
filename = select_input_file_path()
# excel_filename = select_output_file_path()

# 初始化存储内容块的列表
blocks = []
current_block = ""

# 正则表达式模式
timestamp_pattern = re.compile(r'\[(\d{2}:\d{2}:\d{2}\.\d{3})\]')
correct_pattern = re.compile(rf'^\[\d{{2}}:\d{{2}}:\d{{2}}\.\d{{3}}\].*?{KEYWORD}.*?=\d+\.\d{{2}}$')

print(correct_pattern)
with open(filename, 'r', encoding='GB2312') as file:
    for line in file:
        # 预处理每行内容
        cleaned_line = line.replace('收←◆', '').strip()
        if not cleaned_line:
            if current_block:
                # 提取第一个时间戳并清理内容
                match = timestamp_pattern.search(current_block)
                if match:
                    first_ts = match.group(0)
                    cleaned_block = timestamp_pattern.sub('', current_block)
                    cleaned_block = first_ts + cleaned_block.replace(" ", "")
                    # 验证格式是否正确
                    if correct_pattern.match(cleaned_block):
                        blocks.append(cleaned_block)
            current_block = ""
        else:
            current_block += cleaned_line

# 处理最后一个块
if current_block:
    match = timestamp_pattern.search(current_block)
    if match:
        first_ts = match.group(0)
        cleaned_block = timestamp_pattern.sub('', current_block)
        cleaned_block = first_ts + cleaned_block.replace(" ", "")
        if correct_pattern.match(cleaned_block):
            blocks.append(cleaned_block)

# 提取数据
data = []
pattern = re.compile(
    rf'\[(\d{{2}}:\d{{2}}:\d{{2}}\.\d{{3}})\].*?{KEYWORD}.*?=(\d+\.\d{{2}})'
)

for block in blocks:
    match = pattern.search(block)
    if match:
        timestamp = match.group(1)
        value = float(match.group(2))
        data.append([timestamp, value])

# 导出到Excel
if data:
    df = pd.DataFrame(data, columns=['时间戳', '检测值'])
    
    # 计算统计值
    avg = df['检测值'].mean()
    max_val = df['检测值'].max()
    min_val = df['检测值'].min()
    
    # 添加统计行
    df = pd.concat([
        df,
        pd.DataFrame([['平均值', avg]], columns=df.columns),
        pd.DataFrame([['最大值', max_val]], columns=df.columns),
        pd.DataFrame([['最小值', min_val]], columns=df.columns)
    ], ignore_index=True)
    
    # df.to_excel(excel_filename, index=False)
    # print(f"数据已导出到: {excel_filename}")
    print(f"平均值: {avg:.2f}, 最大值: {max_val:.2f}, 最小值: {min_val:.2f}")
else:
    print("未找到有效数据")